package com.zhiquan.cai.config;

import com.zhiquan.cai.entity.User;
import com.zhiquan.cai.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义Realm
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    // 授权处理
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    // 认证处理
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 编写Shiro判断逻辑，判断账号和密码
        // 1、判断账号
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        User user = userService.findByUsername(token.getUsername());
        if (user == null) {
            // 账号错误，Shiro底层会抛出UnknownAccountException异常
            return null;
        }

        // 2、判断密码
        return new SimpleAuthenticationInfo("", user.getPassword(), "");
    }
}